package xyz.mimai.media.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

    /**
     * 写文件
     * @param content
     * @param filePath
     */
    public static void writeContentToFile(String content,String filePath){
        //创建一个buffer，按实际内容分配buffer大小
        ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());

//        ByteBuffer byteBuffer01 = ByteBuffer.allocate(content.getBytes().length);
//        byteBuffer01.put(content.getBytes());
        //反转buffer的模式为读模式
        byteBuffer.flip();
        try(FileOutputStream fo = new FileOutputStream(filePath); FileChannel channel = fo.getChannel()) {
            while(byteBuffer.hasRemaining()) {
                channel.write(byteBuffer);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 将原文件的内容复制到一个新文件，直接通过buffer交换数据，简单高效
     * @param sourceFilePath
     * @param targetFilePath
     */
    public static void readContentToAnotherFile(String sourceFilePath,String targetFilePath){
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        try(FileInputStream inputStream = new FileInputStream(sourceFilePath);
            FileChannel readChannel = inputStream.getChannel();
            FileOutputStream fo = new FileOutputStream(targetFilePath);
            FileChannel writeChannel = fo.getChannel()) {
            //读取文件到buffer
            readChannel.read(byteBuffer);

            byteBuffer.put("\n".getBytes());
            byteBuffer.put("copy successful".getBytes());

            //反转buffer的模式为读模式
            byteBuffer.flip();

            if(byteBuffer.hasRemaining()){
                while(byteBuffer.hasRemaining()) {
                    writeChannel.write(byteBuffer);
                }
                //写完再次反转为写模式，为下次做准备
                byteBuffer.flip();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void copyFile(String sourceFilePath,String targetFilePath){
        try(FileChannel inputChannel = new FileInputStream(sourceFilePath).getChannel();
            FileChannel outputChannel = new FileOutputStream(targetFilePath).getChannel();) {
            //两种写法都是可以的，只是主动和被动方的表现形式不一样
            // inputChannel.transferTo(0,inputChannel.size(),outputChannel);
            outputChannel.transferFrom(inputChannel,0,inputChannel.size());

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
    //    writeContentToFile("hello,i am fileChannel demo.","f:\\code\\we-media\\channelTxt1.txt");

//        readContentToAnotherFile("E:\\code\\we-media\\channelTxt1.txt","f:\\code\\we-media\\channelTxt2.txt");

        copyFile("f:\\code\\we-media\\channelTxt1.txt","f:\\code\\we-media\\channelTxt3.txt");
    }

}
